package com.gcd.alienandwheel.actor;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.utils.MathUtils;

/**
 *
 * @author Rezan Achmad
 */
public class Bar extends MyActor {

    Pixmap pixmap;
    float value;
    float maxValue;
    boolean horizontal;

    public Bar(String name, float maxValue, float width, float height, Color color, boolean horizontal) {
        super(name);
        this.width = width;
        this.height = height;
        this.maxValue = maxValue;
        originX = width / 2;
        originY = height / 2;
        pixmap = new Pixmap(MathUtils.nextPowerOfTwo((int) width), MathUtils.nextPowerOfTwo((int) height), Pixmap.Format.RGBA8888);
        texture = new Texture(pixmap);
        value = 0;
        this.horizontal = horizontal;
        color.set(color);
    }

    public void setColor(Color color) {
        color.set(color);
    }

    public void setValue(float value) {
        if (value > maxValue) {
            value = maxValue;
        }

        if (value < 0) {
            value = 0;
        }

        this.value = value;
    }

    public float getMaxValue() {
        return maxValue;
    }

    @Override
    protected void draw(SpriteBatch batch, float parentAlpha) {
        pixmap.setColor(0, 0, 0, 0);
        pixmap.fill();

        int tWidth;
        int tHeight;

        if (horizontal) {
            tWidth = (int) (value / maxValue * width);
            tHeight = (int) height;
        } else {
            tWidth = (int) width;
            tHeight = (int) (value / maxValue * height);
            rotation = 180;
        }

        pixmap.setColor(0, 0, 0, 1);
        pixmap.drawRectangle(0, 0, (int) width, (int) height);
        pixmap.setColor(color.r, color.g, color.b, color.a);
        pixmap.fillRectangle(1, 1, tWidth - 2, tHeight - 2);

        setTexture(pixmap);
        super.draw(batch, parentAlpha);
    }

    @Override
    protected boolean touchDown(float x, float y, int pointer) {
        return hit(x, y) != null;
    }

    @Override
    protected boolean touchUp(float x, float y, int pointer) {
        return hit(x, y) != null;
    }

    @Override
    protected boolean touchDragged(float x, float y, int pointer) {
        return hit(x, y) != null;
    }

    @Override
    public Actor hit(float x, float y) {
        return (x > 0 && y > 0 && x < width && y < height) ? this : null;
    }
}
